<template>
  <div class="map-container">
    <div class="search-container">
      <input
        type="text"
        v-model="searchQuery"
        placeholder="搜索模型名称..."
        class="search-input"
        @input="handleSearchInput"
        @keyup.enter="handleSearchSubmit"
      />
      <div v-if="searchResults.length > 0" class="search-results">
        <div
          v-for="item in searchResults"
          :key="item.id"
          class="search-result-item"
          @click="locateToPosition(item)"
        >
          {{ item.name || `模型 ${item.id}` }}
        </div>
      </div>
    </div>
    <div id="map" ref="mapContainer" class="map"></div>

    <!-- 导入的颜色切换组件 -->
    <ColorSwitcher @color-change="handleColorChange" />

    <!-- 模型查看器弹窗 -->
    <ModelViewer
      v-model:visible="modelViewerVisible"
      :model-url="currentModelUrl"
      :model-name="currentModelName"
      :model-id="currentModelId"
      @close="handleModelViewerClose"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from "vue";
import {
  TMapLoader,
  MapService,
  ModelService,
  modelData,
  type MapDataItem,
} from "@/utils/index";
import ColorSwitcher from "./ColorSwitcher.vue";
import ModelViewer from "./ModelViewer.vue";

// 地图容器
const mapContainer = ref<HTMLElement | null>(null);
let TMap = null;
let mapService: MapService | null = null;
let modelService: ModelService | null = null;
let infoWindowService: any = null;

// 搜索相关状态
const searchQuery = ref("");
const searchResults = ref<MapDataItem[]>([]);

// 模型查看器状态
const modelViewerVisible = ref(false);
const currentModelUrl = ref('');
const currentModelName = ref('');
const currentModelId = ref('');

/**
 * 初始化地图
 */
const initMap = async () => {
  if (!mapContainer.value) return;

  try {
    // 使用TMapLoader加载腾讯地图API
    TMap = await TMapLoader(import.meta.env.VITE_TENCENT_MAP_KEY);

    // 创建地图服务实例
    mapService = new MapService(TMap);

    // 初始化地图
    const mapInstance = await mapService.initMap(mapContainer.value);

    if (mapInstance && TMap) {
      // 创建模型服务实例
      modelService = new ModelService(TMap, mapInstance);

      // 获取ModelService内部的InfoWindowService实例
      infoWindowService = modelService.getInfoWindowService();

      // 设置地图事件处理
      setupMapEvents();

      // 初始化时检查缩放级别，只在14-20之间创建模型
      const currentZoom = mapService.getZoom();
      if (currentZoom >= 15 && currentZoom <= 20) {
        loadModelsInViewport();
      }
    }
  } catch (error) {
    console.error("地图初始化失败:", error);
  }
};

/**
 * 设置地图事件处理
 */
const setupMapEvents = () => {
  if (!mapService) return;

  // 添加地图事件监听
  mapService.on("zoomend", handleZoomChange);
  mapService.on("rotateend", handleRotateChange);
  mapService.on("moveend", handleMoveEnd);
};

/**
 * 处理颜色配置切换
 * @param config 颜色配置对象
 */
const handleColorChange = (config: any) => {
  try {
    // 尝试通过infoWindowService设置颜色配置
    if (
      infoWindowService &&
      typeof infoWindowService.setColorConfig === "function"
    ) {
      infoWindowService.setColorConfig(config);
      console.log("颜色配置已通过infoWindowService设置:", config);
    }
    // 如果失败，尝试通过modelService获取infoWindowService
    else if (
      modelService &&
      typeof modelService.getInfoWindowService === "function"
    ) {
      const service = modelService.getInfoWindowService();
      if (service && typeof service.setColorConfig === "function") {
        service.setColorConfig(config);
        console.log("颜色配置已通过modelService设置:", config);
      }
    }
  } catch (error) {
    console.error("切换颜色配置失败:", error);
  }
};

/**
 * 处理搜索输入
 */
const handleSearchInput = () => {
  if (!searchQuery.value.trim()) {
    searchResults.value = [];
    return;
  }

  // 根据输入过滤模型数据
  searchResults.value = modelData.filter((item: MapDataItem) => {
    const searchLower = searchQuery.value.toLowerCase();
    const nameLower = (item.name || "").toLowerCase();
    const idLower = (item.id || "").toString().toLowerCase();

    return nameLower.includes(searchLower) || idLower.includes(searchLower);
  });
};

/**
 * 处理搜索提交
 */
const handleSearchSubmit = () => {
  if (searchResults.value.length > 0) {
    locateToPosition(searchResults.value[0]);
  }
};

/**
 * 定位到指定位置
 * @param item 模型数据项
 */
const locateToPosition = (item: MapDataItem): void => {
  if (!mapService) return;

  try {
    // 使用地图服务定位到指定位置
    mapService.locateToPosition(item);

    // 清空搜索结果和输入
    searchQuery.value = "";
    searchResults.value = [];

    // 重新加载视口内的模型
    nextTick(() => {
      loadModelsInViewport();
    });
  } catch (error) {
    console.error("定位失败:", error);
  }
};

/**
 * 加载当前视口内的模型
 */
const loadModelsInViewport = () => {
  if (!modelService) return;

  modelService.loadModelsInViewport(modelData);
};

/**
 * 清理所有模型实例
 */
const clearAllModels = async (): Promise<void> => {
  if (modelService) {
    modelService.clearAllModels();
  }
};

// 处理地图缩放变化 - 控制模型显示/隐藏
const handleZoomChange = () => {
  if (!mapService || !modelService) return;

  const currentZoom = mapService.getZoom();
  console.log("地图缩放级别变化为:", currentZoom);

  // 只在缩放级别17-20之间显示模型
  if (currentZoom >= 15 && currentZoom <= 20) {
    // 加载当前视口内的模型
    loadModelsInViewport();
  } else {
    // 清理所有模型实例
    if (modelService.getModelCount() > 0) {
      console.log("销毁所有模型实例，当前缩放级别不适合显示模型");
      clearAllModels();
    }
  }
};

// 处理地图移动结束事件 - 重新加载视口内的模型
const handleMoveEnd = () => {
  if (!mapService || !modelService) return;

  if (modelService.getModelCount() === 0) return;

  const currentZoom = mapService.getZoom();
  // 只在缩放级别15-20之间重新加载模型
  if (currentZoom >= 15 && currentZoom <= 20) {
    console.log("地图移动结束，重新加载视口内模型");
    loadModelsInViewport();
  }
};

// 处理地图旋转变化
const handleRotateChange = () => {};

onMounted(async () => {
  // 先销毁所有模型实例 后创建
  await clearAllModels();
  await initMap();

  console.log("地图初始化完成", modelData);
});

// 组件卸载时销毁地图实例
onUnmounted(() => {
  // 销毁所有模型实例
  if (modelService) {
    modelService.destroy();
    modelService = null;
  }

  // 销毁地图服务
  if (mapService) {
    mapService.destroy();
    mapService = null;
  }
});

/**
 * 全局方法：加载Three.js模型
 * 这个方法会被信息窗口中的按钮调用
 */
(window as any).loadThreeJSModel = (modelId: string, modelName: string, modelUrl: string, lat: number, lon: number) => {
  console.log(`全局方法被调用 - 模型ID: ${modelId}, 名称: ${modelName}, URL: ${modelUrl}`);
  
  // 打开模型查看器弹窗
  currentModelId.value = modelId;
  currentModelName.value = modelName;
  currentModelUrl.value = modelUrl;
  modelViewerVisible.value = true;
};

/**
 * 处理模型查看器关闭
 */
const handleModelViewerClose = () => {
  modelViewerVisible.value = false;
  currentModelUrl.value = '';
  currentModelName.value = '';
  currentModelId.value = '';
};
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100%;
  position: relative; /* 设置为相对定位，使模型容器的绝对定位相对于地图容器 */
}

.map {
  width: 100%;
  height: 100%;
}

/* 搜索框样式 */
.search-container {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 3000;
  width: 300px;
}

.search-input {
  width: 100%;
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  outline: none;
  transition: box-shadow 0.3s ease;
}

.search-input:focus {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.search-results {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  margin-top: 5px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  max-height: 200px;
  overflow-y: auto;
}

.search-result-item {
  padding: 10px 15px;
  cursor: pointer;
  font-size: 14px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s ease;
}

.search-result-item:hover {
  background-color: #f5f5f5;
}

.search-result-item:last-child {
  border-bottom: none;
}

/* 调试信息样式 */
.debug-info {
  position: absolute;
  top: 10px;
  left: 10px;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 10px;
  border-radius: 5px;
  font-size: 12px;
  line-height: 1.4;
  color: #333;
  z-index: 2000;
  max-width: 300px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #ddd;
}

.debug-info p {
  margin: 0;
  padding: 2px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 颜色切换组件样式 */
</style>
